package com.tongandtang.entity;

import com.tongandtang.bg.entity.Perm;
import com.tongandtang.bg.entity.User;
import com.tongandtang.security.PermCacheManager;
import com.tongandtang.utils.SpringUtil;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class UserDetailsImpl implements UserDetails {

    public UserDetailsImpl(User user,String username){
        this.username=username;
        this.password=user.getPassword();
        this.id=user.getId();
        this.deleted=user.getDeleted();
    }

    private String username;

    private String password;

    private Long id;

    private Integer deleted;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        PermCacheManager permCacheManager= SpringUtil.getBean(PermCacheManager.class);
        try {
            List<Perm> perms = permCacheManager.getPerm(id);
            List<GrantedAuthority> permList=new ArrayList<>();
            for(Perm perm:perms){
                permList.add(new SimpleGrantedAuthority(perm.getPerm()));
            }
            return permList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return deleted == 0;
    }
}
